﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YJKFloor.FloorOffset;
using YJKFloor.Forms;
using YJKFloor.Utility;

namespace YJKFloor.FloorEditor
{
	public class FloorOffsetEditor
	{
		public FloorOffsetEditor(ExternalCommandData cmdData)
		{
			this.m_Revit = cmdData;
			this.m_Doc = this.m_Revit.Application.ActiveUIDocument.Document;
		}

		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Offset(ref string msg)
		{
			FloorOffsetForm floorOffsetForm = new FloorOffsetForm();
			floorOffsetForm.Show(CmdFloorOffset._hWndRevit);
			int wMsg = 7;
			FloorOffsetEditor.SendMessage(CmdFloorOffset._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			Result result;
			try
			{
				for (;;)
				{
					List<Floor> list = new List<Floor>();
					if (!this.SelectFloors(ref list))
					{
						break;
					}
					foreach (Floor floor in list)
					{
						this.OffsetFloor(floor, floorOffsetForm.Offset);
					}
					if (list.Count > 0)
					{
						MessageBox.Show("楼板修改成功。", "盈建科提示");
					}
				}
				floorOffsetForm.Close();
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception)
			{
				floorOffsetForm.Close();
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}

		private bool SelectFloors(ref List<Floor> floors)
		{
			IList<Reference> list = null;
			Selection selection = this.m_Revit.Application.ActiveUIDocument.Selection;
			try
			{
				list = selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Element, new FloorFilter(), "框选要升降的楼板");
			}
			catch (Exception)
			{
				return false;
			}
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			foreach (Reference reference in list)
			{
				Element element = document.GetElement(reference);
				Floor item = element as Floor;
				floors.Add(item);
			}
			return true;
		}

		private void OffsetFloor(Floor floor, double offset)
		{
			Transaction transaction = new Transaction(this.m_Doc);
			transaction.Start("set floor offset");
			try
			{
				double num = floor.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM).AsDouble();
				floor.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM).Set(offset + num);
				transaction.Commit();
			}
			catch (Exception)
			{
				transaction.RollBack();
			}
		}

		private ExternalCommandData m_Revit;

		private Document m_Doc;
	}
}
